package ar.org.sstuyv.familiaPropietaria

import grails.converters.JSON

import org.springframework.dao.DataIntegrityViolationException

import ar.org.sstuyv.EstadoCivil
import ar.org.sstuyv.NomenclaturaCatastral
import ar.org.sstuyv.Partido
import ar.org.sstuyv.User

class CensosController {

//    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [censosInstanceList: Censos.list(params), censosInstanceTotal: Censos.count()]
    }

    def create() {
        [censosInstance: new Censos(params)]
    }

//    def save() {
//        def censosInstance = new Censos(params)
//        if (!censosInstance.save(flush: true)) {
//            render(view: "create", model: [censosInstance: censosInstance])
//            return
//        }
//
//        flash.message = message(code: 'default.created.message', args: [message(code: 'censos.label', default: 'Censos'), censosInstance.id])
//        redirect(action: "show", id: censosInstance.id)
//    }

    def show(Long id) {
        def censosInstance = Censos.get(id)
        if (!censosInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'censos.label', default: 'Censos'), id])
            redirect(action: "list")
            return
        }

        [censosInstance: censosInstance]
    }

    def edit(Long id) {
        def censosInstance = Censos.get(id)
        if (!censosInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'censos.label', default: 'Censos'), id])
            redirect(action: "list")
            return
        }

        [censosInstance: censosInstance]
    }

//    def update(Long id, Long version) {
//        def censosInstance = Censos.get(id)
//        if (!censosInstance) {
//            flash.message = message(code: 'default.not.found.message', args: [message(code: 'censos.label', default: 'Censos'), id])
//            redirect(action: "list")
//            return
//        }
//
//        if (version != null) {
//            if (censosInstance.version > version) {
//                censosInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
//                          [message(code: 'censos.label', default: 'Censos')] as Object[],
//                          "Another user has updated this Censos while you were editing")
//                render(view: "edit", model: [censosInstance: censosInstance])
//                return
//            }
//        }
//
//        censosInstance.properties = params
//
//        if (!censosInstance.save(flush: true)) {
//            render(view: "edit", model: [censosInstance: censosInstance])
//            return
//        }
//
//        flash.message = message(code: 'default.updated.message', args: [message(code: 'censos.label', default: 'Censos'), censosInstance.id])
//        redirect(action: "show", id: censosInstance.id)
//    }

    def delete(Long id) {
        def censosInstance = Censos.get(id)
        if (!censosInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'censos.label', default: 'Censos'), id])
            redirect(action: "list")
            return
        }

        try {
            censosInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'censos.label', default: 'Censos'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'censos.label', default: 'Censos'), id])
            redirect(action: "show", id: id)
        }
    }
	
	
	def listJSON = {
		
		def sortIndex = params.sidx ?: 'id'
		def sortOrder  = params.sord ?: 'asc'
		//def informes = InformesUrbanisticos.findAll()
		def maxRows = Integer.valueOf(params?.rows)
		def currentPage = Integer.valueOf(params.page) ?: 1
		def rowOffset = currentPage == 1 ? 0 : (currentPage - 1) * maxRows
		
		def censos = Censos.createCriteria().list(max: maxRows, offset: rowOffset) {
			order(sortIndex, sortOrder)
		}
		
		def totalRows = censos.totalCount
		def numberOfPages = Math.ceil(totalRows / maxRows)
		
		def results = censos?.collect {
			
			[
				cell: [it.partido?.nombre, it.nombre, it.CUIL, it.estadoCivil?.descripcion, it.plan?.nombre,
					it.esMenor, 
					it.nomenclaturaDefinitiva?.spartido +' '+ it.nomenclaturaDefinitiva?.circunscripcion +' '+ it.nomenclaturaDefinitiva?.seccion +' '+
					it.nomenclaturaDefinitiva?.numeroChacra + it.nomenclaturaDefinitiva?.letraChacra +' '+
					it.nomenclaturaDefinitiva?.numeroQuinta + it.nomenclaturaDefinitiva?.letraQuinta +' '+
					it.nomenclaturaDefinitiva?.numeroFraccion + it.nomenclaturaDefinitiva?.letraFraccion,
					it.nomenclaturaDefinitiva?.id,
					],
				 id: it.id
			]
		}
		
		def jsonData = [rows: results, page: currentPage, records: totalRows, total: numberOfPages]
		
		render jsonData as JSON
	}
	
	def fileSave =  {
		
		def uploadedFile = request.getFile('ARCHIVOIIUU')
		if (uploadedFile?.size > 0){
			User user = springSecurityService.getCurrentUser()
			
			def webRootDir = servletContext.getRealPath("/")
			
			def userDir = new File(webRootDir, "/IIUU/" + user?.username + "/" )
			userDir.mkdirs()
			uploadedFile.transferTo( new File( userDir, uploadedFile?.fileItem.fileName))
			
		}
		render ''
	}
	
	def save = {
		
		def censosInstance = new Censos()
		
		Partido partido = Partido.findById(params.partido)
		censosInstance.setPartido(partido)
		
		EstadoCivil estadoCivil = EstadoCivil.findById(params.estadoCivil)
		censosInstance.setEstadoCivil(estadoCivil)
		
		PlanSocial plan = PlanSocial.findById(params.plan)
		censosInstance.setPlan(plan)
		
		censosInstance.setNombre(params.nombre)
		
		censosInstance.esMenor(params.esMenor)
		
		censosInstance.setCUIL(params.CUIL)
		
		censosInstance.save(failOnError:true)
		
		NomenclaturaCatastral nomenclatura = NomenclaturaCatastral.findById(params.nomenclaturaOrigenId)
		informeTecnicoUrbanisticoInstance.setNomenclaturaOrigen(nomenclatura)
		
		render ""

	}
	
	def update =  {
		def censosInstance = Censos.get(params.id.toLong())
		if (censosInstance) {
			if (params.version) {
				def version = params.version.toLong()
				if (censosInstance.version > version) {
					render "error"
				}
			}
			
			Partido partido = Partido.findById(params.partido)
			censosInstance.setPartido(partido)
			
			EstadoCivil estadoCivil = EstadoCivil.findById(params.estadoCivil)
			censosInstance.setEstadoCivil(estadoCivil)
			
			PlanSocial plan = PlanSocial.findById(params.plan)
			censosInstance.setPlan(plan)
			
			censosInstance.setNombre(params.nombre)
			
			censosInstance.setCUIL(params.CUIL)

			NomenclaturaCatastral nomenclatura = NomenclaturaCatastral.findById(params.nomenclaturaOrigenId)
			informeTecnicoUrbanisticoInstance.setNomenclaturaOrigen(nomenclatura)
			
			def esMenor = params.esMenor
			
			if(esMenor == "on"){
				esMenor = true
			} else {
				esMenor = false
			}
			
			censosInstance.setEsMenor(esMenor)
			
			if (censosInstance.save(flush: true)) {
				render "success" //�?
				
			}
			else {
				render "error"
			}
		}
		else {
			render "error"
		}
	}
	
	
	
}
